package com.tnsw.facebookautoliker.helper.command;

import java.util.ArrayList;

import org.json.JSONObject;

import android.content.Context;

import com.facebook.Response;
import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.ObjectCache;
import com.tnsw.facebookautoliker.helper.FacebookActionListener;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;

public class GetPhotoFQL extends FacebookCommandObject implements FacebookActionListener, FQLInterface {

	private String xid;
	private String description;
	private String post_id;
	
	private FacebookBGManager fbm;
	private DBManager dbm;
	private GeneralManager gm;
	
	private FQLBase fqlb;
	private GetHTTPPhoto gp;
	
	private String signature;
	
	public GetPhotoFQL(Context context, String xid, String description, String post_id) {
		super(context);
		super.tag = "GetPhotoFQL";
		this.xid = xid;
		
		this.description = description;
		this.post_id = post_id;
		this.signature = this.getClass().getName() + "_" + xid + "_" + post_id;
		
		this.fbm = FacebookBGManager.getInstance(context);
		this.dbm = DBManager.getInstance(context);
		this.gm = GeneralManager.getInstance();
		
		this.fbm.registerActionListener(this);
		this.setApplyCounter(false);
		this.setChildrenCommandCount(2);
		this.setRequiredSignature(true);
	}

	@Override
	public String getSignature() {
		return(this.signature);
	}
	
	@Override
	protected void handleResult(Response response) {
		super.handleResult(response);
	}

	@Override
	public void execute() {
		super.execute();
		
		String fql;
		
		this.fqlb = new FQLBase(this.context, null);
		if (this.description.contains("video")) {
			fql = "select owner, thumbnail_link, src, created_time from video where vid='" + this.xid + "'";
			this.fqlb.setTag("type", "video");
		} else {
			fql = "select src, src_big, created from photo where object_id='" + this.xid + "'";
			this.fqlb.setTag("type", "photo");
		}
		
		this.fqlb.setParent(this);
		
		this.fqlb.setFQL(fql);
		
		this.fqlb.setFQLInterface(this);
		this.fqlb.setMaxRecord(1);
		this.fqlb.setPagingColumn(null);
		
		this.fqlb.execute();
	}

	@Override
	public void onRequestCompleted(Object sender, FacebookCommandObject fbco, int statusCode, Exception tr) {
		if (fbco.equals(this.gp)) {
			
			MyLog.d(tag, "Got Photo, " + this.gp.getPhotoPath());
			if (gp.getTag("record") != null) {
				ObjectCache oc = (ObjectCache) gp.getTag("record");
				oc.local_path = this.gp.getPhotoPath();
				this.dbm.updateRecordByPrimarykey("object_cache", oc, true);
				MyLog.d(tag, "updated object_cache, fbid=" + oc.fbid);
			}
			
			this.fbm.updateCommandStatus(this, statusCode, tr);
		}
	}

	@Override
	public boolean onSingleRecordFetched(Object sender, int recordNo, JSONObject jo) {
		MyLog.d(tag, "onSingleRecordFetched()");
		
		if (sender == this.fqlb) {
			try {
				
				if (this.fqlb.getTag("type").equals("video")) {
					String thumbnail_link = jo.getString("thumbnail_link");
					String src = jo.getString("src");
					
					MyLog.d(tag, "downloading video thumbnail=" + thumbnail_link);
					ObjectCache oc = null;
					ArrayList<RecordBase> a = this.dbm.getRecords(ObjectCache.class.getName(), "select * from object_cache where fbid=?", new String[] {this.xid}, 0);
					if (a == null) {
						int created_time = jo.getInt("created_time");
						String owner = jo.getString("owner");
						
						oc = new ObjectCache();
						oc.primarykey = this.dbm.getNewPrimarykey();
						oc.type = "photo";
						oc.fbid = this.xid;
						oc.src = thumbnail_link;
						oc.created_time = created_time;
						oc.local_path = "";
						oc.owner = owner;
						oc.post_id = this.post_id;
						oc.source_url = "";
						
						this.dbm.insertRecord("object_cache", oc, null, true);
						MyLog.d(tag, "inserted object_cache, fbid=" + oc.fbid);
						
					} else {
						oc = (ObjectCache) a.get(0);
						MyLog.d(tag, "record exists, oc=" + oc.toString());
					}
					
					this.gp = new GetHTTPPhoto(context, thumbnail_link, oc.fbid);
					this.gp.setParent(this);
					this.gp.setTag("record", oc);
					//this.gp.setApplyCounter(this.applyCounter());
					this.gp.execute();
					
				} else if (this.fqlb.getTag("type").equals("photo")) {
					String src = jo.getString("src");
					String src_big = jo.getString("src_big");
					
					MyLog.d(tag, "downlong photo=" + src);
				}	
			} catch (Exception e) {
				MyLog.e(tag, "onSingleRecord() - " + e.toString(), e);
			}
			
		}
		
		return(false);
	}

	@Override
	public void onEndQuery(Object sender, ArrayList<JSONObject> arrJ) {
		MyLog.d(tag, "onEndQuery()");
		if ( (arrJ == null) || (arrJ.size() == 0) ) {
			// Not found any record, end parents too.
			FacebookCommandObject fbco = (FacebookCommandObject) sender;
			if (fbco.getLastException() != null) {
				this.setChildrenCommandCount(0);
				this.fbm.updateCommandStatus(this, 400, fbco.getLastException());
				
				
			} else {
				this.setChildrenCommandCount(0);
				this.fbm.updateCommandStatus(this, 200, null);
			}
			
			String sql = "select * from object_cache where fbid=?";
			ArrayList<RecordBase> a = this.dbm.getRecords(ObjectCache.class.getName(), sql, new String[] {this.xid}, 0);
			if (a == null) {
				ObjectCache oc = new ObjectCache();
				oc.primarykey = this.dbm.getNewPrimarykey();
				oc.type = "unknown";
				oc.fbid = this.xid;
				oc.src = "";
				oc.created_time = System.currentTimeMillis() / 1000;
				oc.attempt = 1;
				
				this.dbm.insertRecord("object_cache", oc, null, false);
				MyLog.d(tag, "inserted empty object_cache for fbid=" + this.xid);
			}
		}
	}
}
